package com.example.origin.finance.service.impl;

import cn.hutool.core.util.PageUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.origin.finance.service.AbstractCodeService;
import com.example.origin.resttemplate.util.RestUtil;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Service
public class XueqiuAStockCodeService extends AbstractCodeService {
    private static final String setkeyGuPiao = "gupiao";
    @Override
    protected String codekey() {
        return setkeyGuPiao;
    }

    @Override
    protected void codeConsumer(Set<String> sets) {
        JSONArray gupiao = gupiao();
        for (JSONObject jsonObject : gupiao.toList(JSONObject.class)) {
            String code = jsonObject.get("symbol", String.class);
            String name = jsonObject.get("name", String.class);
            Long market_capital = jsonObject.get("market_capital", Long.class);
            Double pe_ttm = jsonObject.get("pe_ttm", Double.class);
            if (pe_ttm != null && market_capital !=null && !name.contains("ST") && !name.contains("B股")) {
                sets.add(code.substring(2));
            }
        }
    }

    private JSONArray gupiao() {
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Cookie", getXueqiuCookie());

        JSONArray list = new JSONArray();
        JSONObject jsonObject = resultJsonObj(headerMap, 1);
        JSONArray jsonArray = jsonObject.getJSONObject("body").getJSONObject("data").getJSONArray("list");
        list.addAll(jsonArray);
        Integer count = jsonObject.getJSONObject("body").getJSONObject("data").get("count", Integer.class);

        int totalPage = PageUtil.totalPage(count, 90);
        for (int i = 1; i < totalPage; i++) {
            JSONObject jsonObject1 = resultJsonObj(headerMap, i + 1);
            JSONArray jsonArray1 = jsonObject1.getJSONObject("body").getJSONObject("data").getJSONArray("list");
            list.addAll(jsonArray1);
        }

        return list;

    }

    private JSONObject resultJsonObj(Map<String, String> headerMap,int pageNo) {
        String url = "https://stock.xueqiu.com/v5/stock/screener/quote/list.json?page=%s&size=90&order=desc&orderby=percent&order_by=percent&market=CN&type=sh_sz";
        String url2 = String.format(url, pageNo+"");
        ResponseEntity<String> response = RestUtil.restGet(restTemplate, url2, null, headerMap, ParameterizedTypeReference.forType(String.class));
        return JSONUtil.parseObj(response);
    }
}
